package cn.com.haopy.yue.ai.wx.service;


import cn.com.haopy.yue.ai.core.config.storage.StorageService;
import cn.com.haopy.yue.ai.core.system.SystemConfig;
import cn.com.haopy.yue.ai.core.utils.ResponseUtil;
import cn.com.haopy.yue.ai.db.entity.arisk.*;
import cn.com.haopy.yue.ai.db.service.hos.*;
import cn.com.haopy.yue.ai.wx.dto.AIPdfResDto;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 风险评估报告地址pdf
 */
@Service
@Slf4j
public class WxPaperPdfService {

    @Autowired
    private PdfAiApiService pdfAiApiService;

    @Autowired
    private AIRiskPapersService riskPapersService;

    @Autowired
    private AIRiskIllnessService riskIllnessService;

    @Autowired
    private AIRiskIllnessCheckIndexService riskIllnessCheckIndexService;

    @Autowired
    private AIRiskCheckIndexService riskCheckIndexService;

    @Autowired
    private AIRiskPapersIllnessService riskPapersIllnessService;

    @Autowired
    private AIRiskPapersIndexService riskPapersIndexService;

    @Autowired
    private StorageService storageService;


    @Autowired
    private AIRiskPapersOptionsService riskPapersOptionsService;


    /**
     * 生成pdf
     *
     * @param paperId
     * @return
     */
    public Object createPdfByPaperId(Integer paperId) {
        try {
            ClassPathResource resource = new ClassPathResource("data/test.json");
            byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
            String str = new String(bytes, StandardCharsets.UTF_8);

            JSONObject data = JSONObject.parseObject(str);

            AIRiskPapers paper = riskPapersService.getById(paperId);

            if (Objects.nonNull(paper)) {
                //体检信息
                JSONObject persion = new JSONObject();
                persion.put("name", paper.getName());
                persion.put("healthId", paper.getCheckNo());
                persion.put("sex", paper.getSex());
                persion.put("sexVal", paper.getName());
                persion.put("age", paper.getAge());
                persion.put("birthday", "");
                persion.put("company", "云南昊邦");
                persion.put("checkDate", paper.getCheckDate());
                persion.put("usedSystem", "");

                data.put("persion", persion);

                //疾病
                JSONArray diseases = new JSONArray();

                List<AIRiskPapersIllness> papersIllnessList = riskPapersIllnessService.getByPapersId(paperId);
                for (AIRiskPapersIllness papersIllnessItem : papersIllnessList) {
                    JSONObject illnessJson = new JSONObject();
                    illnessJson.put("diseaseName", papersIllnessItem.getIllnessName());
                    illnessJson.put("title", papersIllnessItem.getQuestion());
                    illnessJson.put("usedSystem", "");


                    //指标风险
                    JSONArray riskList = new JSONArray();

                    //疾病指标
                    List<AIRiskIllnessCheckIndex> illnessCheckindexList = riskIllnessCheckIndexService.getByIllnessId(papersIllnessItem.getIllnessId());

                    //问卷指标
                    List<AIRiskPapersIndex> papersIndexList = riskPapersIndexService.getNotEmptyByPapersId(paperId);

                    for (AIRiskIllnessCheckIndex illnessCheckIndexItem : illnessCheckindexList) {
                        if (Objects.nonNull(illnessCheckIndexItem)) {
                            for (AIRiskPapersIndex papersIndexItem : papersIndexList) {
                                if (illnessCheckIndexItem.getIndexId().equals(papersIndexItem.getIndexId())) {
                                    if (Objects.isNull(papersIndexItem.getIllnessId()) || papersIllnessItem.getIllnessId().equals(papersIndexItem.getIllnessId())) {
                                        JSONObject indexItem = new JSONObject();
                                        indexItem.put("judgeName", papersIndexItem.getIndexName());
                                        indexItem.put("judgeNormalVal", papersIndexItem.getNormalVal());
                                        indexItem.put("isShow", 1);
                                        indexItem.put("judgeValue", papersIndexItem.getIndexValue());
                                        indexItem.put("judgeScore", 0);
                                        indexItem.put("judgeState", "1");
                                        riskList.add(indexItem);
                                    }
                                }
                            }
                        }
                    }

                    illnessJson.put("riskList", riskList);


                    //模型返回 json数据
                    Map<String, Object> resultJson = papersIllnessItem.getResultJson();

                    try {
                        //图表数据
                        Map<String, Object> content = (Map<String, Object>) resultJson.get("content");
                        Map<String, Object> risk_analise = (Map<String, Object>) content.get("risk_analise");

                        JSONObject riskAnalysis = new JSONObject();
                        //当前风险
                        riskAnalysis.put("currentRiskLevel", ((Map<String, String>) risk_analise.get("currentRiskLevel")).get("riskLevel").split("，")[0]);
                        //患病风险
                        riskAnalysis.put("futureRiskWithIntervention", ((Map<String, String>) risk_analise.get("getDiseaseRisk")).get("riskLevel").split("，")[0]);
                        //可降至风险
                        riskAnalysis.put("futureRiskWithoutIntervention", ((Map<String, String>) risk_analise.get("futureRiskWithIntervention")).get("riskLevel").split("，")[0]);

                        illnessJson.put("riskAnalysis", riskAnalysis);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error(e.toString());
                    }

                    JSONArray listContent = getListContent(papersIllnessItem, resultJson);

                    illnessJson.put("conten", listContent);

                    illnessJson.put("riskLevel", papersIllnessItem.getRisk());


                    diseases.add(illnessJson);
                }


                data.put("diseases", diseases);

                //疾病图表分析----汇总-----

                data.put("diseasesAnalysis", getDiseasesAnalysis(paperId, data.getJSONObject("diseasesAnalysis")));


                //高风险指标

                data.put("diseasesMaxRiskItem9", getMaxRiskItem9Exception(paper));

                //疾病部位数据关系
                data.put("people", getPeoplePartIllness(paper, data.getJSONObject("people")));

                //疾病等级
                data.put("riskLevelList", JSONArray.parse(SystemConfig.getSystemRiskLevelList()));

                //健康信息汇总
                data.put("healthInfo", getHealthInfo(paper, data.getJSONArray("healthInfo")));


                AIPdfResDto resDto = pdfAiApiService.createPdf(data);

                if (resDto.getSuccess()) {


                    try {
                        URI uri = new URI(resDto.getUrl());
                        URL obj = uri.toURL();
                        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
                        conn.setReadTimeout(60_000);// 30秒读取超时
                        conn.setConnectTimeout(10_000); // 10秒连接超时

                        // 先获取内容长度（可能不可用）
                        long contentLength = conn.getContentLengthLong();


                        HOSStorage storage = storageService.store(conn.getInputStream(), contentLength, "image/pdf", "haopy_check_report_" + "66666" + ".pdf");
                        resDto.setUrl(storage.getUrl());

                        System.out.println(storage.getUrl());


                    } catch (Exception e) {
                        log.error("转存到腾讯对象失败，错误：" + e.getMessage());
                        e.printStackTrace();
                    }


                    paper.setPdfUrl(resDto.getUrl());
                    //先设置个默认值
                    //paper.setResultContent(SystemConfig.getSummaryResultContent());
                    riskPapersService.updateById(paper);

                    return ResponseUtil.ok(resDto);
                }


            }


        } catch (Exception e) {
            log.error(e.toString());
            e.printStackTrace();
        }

        return ResponseUtil.fail();

    }

    public JSONArray getListContent(AIRiskPapersIllness papersIllnessItem,//模型返回 json数据
                                    Map<String, Object> resultJson) {

        //图表数据
        Map<String, Object> content = (Map<String, Object>) resultJson.get("content");

        AIRiskIllness illness = riskIllnessService.getById(papersIllnessItem.getIllnessId());
        JSONArray listContent = new JSONArray();
        try {

            JSONObject content1 = new JSONObject();
            String popular = "";
            if (Objects.nonNull(illness)) {
                popular = illness.getPopular();
            }

            content1.put("secondTitle", "");
            content1.put("isStr", "1");
            List<String> items = new ArrayList<>();
            items.add(popular);
            content1.put("items", items);

            listContent.add(content1);
        } catch (Exception e) {
            log.error(e.toString());
        }

        try {


            JSONObject content2 = new JSONObject();

            content2.put("secondTitle", "主要相关指标");
            content2.put("isStr", "1");
            List<String> items = new ArrayList<>();
            items.add("当前状态");
            items.add("名称");
            items.add("本次结果");
            items.add("参考值");
            content2.put("items", items);

            listContent.add(content2);
        } catch (Exception e) {
            log.error(e.toString());
        }

        try {


            Map<String, Object> risk_analise = (Map<String, Object>) content.get("risk_analise");

            JSONObject content3 = new JSONObject();
            content3.put("secondTitle", "风险评估结果");
            content3.put("isStr", "1");
            JSONArray items = new JSONArray();


            JSONObject jo1 = new JSONObject();
            jo1.put("clildTitle", "患病率");
            //Map<String, Object> resultJson = papersIllnessItem.getResultJson();

            jo1.put("childItems", new String[]{((Map<String, String>) risk_analise.get("getDiseaseRisk")).get("riskDesc")});
            items.add(jo1);


            JSONObject jo2 = new JSONObject();
            jo2.put("clildTitle", "当前风险");
            jo2.put("childItems", new String[]{((Map<String, String>) risk_analise.get("currentRiskLevel")).get("riskDesc")});
            items.add(jo2);


            JSONObject jo3 = new JSONObject();
            jo3.put("clildTitle", "可降至风险");
            jo3.put("childItems", new String[]{((Map<String, String>) risk_analise.get("futureRiskWithIntervention")).get("riskDesc")});
            items.add(jo3);


            content3.put("items", items);


            listContent.add(content3);
        } catch (Exception e) {
            log.error(e.toString());
        }

        try {

            Map<String, String> interventions = (Map<String, String>) content.get("interventions");

            JSONObject content4 = new JSONObject();
            content4.put("secondTitle", "预防干预措施");
            content4.put("isStr", "1");
            List<String> items = new ArrayList<>();
            // Map<String, Object> resultJson = papersIllnessItem.getResultJson();
            //生活方式
            //List<String> lifestyle = ((Map<String, List<String>>) resultJson.get("targetedRecommendations")).get("lifestyle");
            items.add("1、生活方式：" + interventions.get("lifestyle"));

            //饮食建议
            //List<String> dietaryPlan = ((Map<String, List<String>>) resultJson.get("targetedRecommendations")).get("dietaryPlan");
            items.add("2、饮食建议：" + interventions.get("dietaryPlan"));

            //检查建议
            //List<String> examinationAdvice = ((Map<String, List<String>>) resultJson.get("targetedRecommendations")).get("examinationAdvice");
            items.add("3、检查建议：" + interventions.get("examinationAdvice"));

            //运动建议
            //List<String> exercisePrescription = ((Map<String, List<String>>) resultJson.get("targetedRecommendations")).get("exercisePrescription");
            items.add("4、运动建议：" + interventions.get("exercisePrescription"));

            content4.put("items", items);

            listContent.add(content4);
        } catch (Exception e) {
            log.error(e.toString());
        }

        try {

            JSONObject content5 = new JSONObject();
            String popular = "";
            if (Objects.nonNull(illness)) {
                popular = illness.getPopularPercent();
            }

            content5.put("secondTitle", "");
            content5.put("isStr", "1");
            List<String> items = new ArrayList<>();
            items.add(popular);
            content5.put("items", items);

            listContent.add(content5);

        } catch (Exception e) {
            log.error(e.toString());
        }

        return listContent;
    }


    /**
     * 疾病汇总分析
     *
     * @param paperId
     * @param analysisData
     * @return
     */
    public JSONObject getDiseasesAnalysis(Integer paperId, JSONObject analysisData) {
        try {
            List<Map<String, Object>> listMap = riskPapersIllnessService.getCountByDisLevel(paperId);
            for (Map<String, Object> map : listMap) {
                String risk = (String) map.get("risk");
                String count = map.get("cn").toString() + "项";
                switch (risk) {
                    case "极低风险":
                        analysisData.put("riskLevel1", count);
                        break;
                    case "低风险":
                        analysisData.put("riskLevel2", count);
                        break;
                    case "中低风险":
                        analysisData.put("riskLevel3", count);
                        break;
                    case "中风险":
                        analysisData.put("riskLevel4", count);
                        break;
                    case "中高风险":
                        analysisData.put("riskLevel5", count);
                        break;
                    case "高风险":
                        analysisData.put("riskLevel6", count);
                        break;
                    case "极高风险":
                        analysisData.put("riskLevel7", count);
                        break;
                    default:
                        break;
                }
            }

        } catch (Exception e) {
            log.error(e.toString());
        }

        return analysisData;

    }


    /**
     * 重点指标
     *
     * @param paper
     * @return
     */
    public JSONArray getMaxRiskItem9(AIRiskPapers paper) {
        JSONArray array = new JSONArray();
        List<Map<String, String>> mapList = riskPapersIndexService.getHasValueByPapersId(paper.getId());
        for (Map<String, String> data : mapList) {
            JSONObject json = new JSONObject();
            json.put("judgeName", data.get("index_name"));
            json.put("judgeNormalVal", data.get("normal_val"));
            json.put("judgeValue", data.get("index_value"));
            json.put("isShow", "1");
            json.put("judgeScore", 100);
            json.put("judgeState", 1);
            array.add(json);
        }

        return array;

    }

    /**
     * 重点指标---异常指标----
     *
     * @param paper
     * @return
     */
    public JSONArray getMaxRiskItem9Exception(AIRiskPapers paper) {
        JSONArray array = new JSONArray();
        //原始采集数据
        Map<String, Object> mapSourceData = paper.getIndexParams();
        //原始指标集
        List<Map<String, String>> listSourceDataIndex = (List<Map<String, String>>) mapSourceData.get("data");
        List<Map<String, String>> mapList = riskPapersIndexService.getHasValueByPapersId(paper.getId());
        for (Map<String, String> data : mapList) {
            for (Map<String, String> itemSourceIndex : listSourceDataIndex) {
                if (data.get("index_name").equals(itemSourceIndex.get("标准项目")) || data.get("index_name").equals(itemSourceIndex.get("检查项目"))) {
                    if (itemSourceIndex.get("提示").equals("↑") || itemSourceIndex.get("提示").equals("↓")) {
                        JSONObject json = new JSONObject();
                        json.put("judgeName", data.get("index_name"));
                        json.put("judgeNormalVal", data.get("normal_val"));
                        json.put("judgeValue", data.get("index_value"));
                        json.put("isShow", "1");
                        json.put("judgeScore", 100);
                        json.put("judgeState", 1);
                        array.add(json);
                        break;
                    }
                }


            }

        }

        return array;

    }

    /**
     * 异常指标----对比报告得出
     *
     * @param paper
     * @return
     */
    public List<AIRiskPapersIndex> getIndexException(AIRiskPapers paper, List<AIRiskPapersIndex> paperIndexList) {
        List<AIRiskPapersIndex> listIndex = new ArrayList<>();
        //原始采集数据
        Map<String, Object> mapSourceData = paper.getIndexParams();
        //原始指标集
        List<Map<String, String>> listSourceDataIndex = (List<Map<String, String>>) mapSourceData.get("data");
        for (AIRiskPapersIndex data : paperIndexList) {
            for (Map<String, String> itemSourceIndex : listSourceDataIndex) {
                if (data.getIndexName().equals(itemSourceIndex.get("标准项目")) || data.getIndexName().equals(itemSourceIndex.get("检查项目"))) {
                    if (itemSourceIndex.get("提示").equals("↑") || itemSourceIndex.get("提示").equals("↓")) {
                        listIndex.add(data);
                        break;
                    }
                }


            }

        }

        return listIndex;

    }


    /**
     * 疾病人体--部位标识
     *
     * @param paper
     * @return
     */
    public JSONObject getPeoplePartIllness(AIRiskPapers paper, JSONObject peopleJonData) {
        List<AIRiskPapersIllness> paperIllnesses = riskPapersIllnessService.getByPapersId(paper.getId());
        try {

            ClassPathResource resource = new ClassPathResource("data/part_illness.json");
            byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
            String str = new String(bytes, StandardCharsets.UTF_8);

            JSONObject partIllnessShipJson = JSONObject.parseObject(str);
            //疾病
            for (AIRiskPapersIllness papersIllnessItem : paperIllnesses) {
                //循环部位
                for (String partName : partIllnessShipJson.keySet()) {
                    //对应的疾病
                    JSONArray partIllnessShipArray = partIllnessShipJson.getJSONArray(partName);

                    if (hasPartIllness(partName, papersIllnessItem, partIllnessShipArray, peopleJonData)) {
                        break;
                    }
                }
            }

        } catch (Exception e) {
            log.error(e.toString());
        }


        return peopleJonData;

    }

    private Boolean hasPartIllness(String partName, AIRiskPapersIllness papersIllnessItem, JSONArray partIllnessShipArray, JSONObject peopleJonData) {
        try {
            //已存在的

            JSONArray existPartArray = peopleJonData.getJSONArray(partName);
            for (int i = 0; i < partIllnessShipArray.size(); i++) {
                JSONObject jsonObject = partIllnessShipArray.getJSONObject(i);
                if (jsonObject.getString("text").equals(papersIllnessItem.getIllnessName())) {
                    JSONObject data = new JSONObject();
                    data.put("text", papersIllnessItem.getIllnessName() + "：" + papersIllnessItem.getRisk());
                    data.put("color", "#FFA500");
                    existPartArray.add(data);
                    return true;
                }
            }

        } catch (Exception e) {
            log.error(e.toString());
        }

        return false;

    }


    /**
     * 健康信息汇总
     *
     * @param paper
     * @param healthInfo
     * @return
     */
    private JSONArray getHealthInfo(AIRiskPapers paper, JSONArray healthInfo) {
        try {

            //return  healthInfo ;


            JSONObject healthInfo1 = healthInfo.getJSONObject(0);

            JSONArray riskList = healthInfo1.getJSONArray("riskList");

            try {
                //第一项
                JSONObject risk1 = riskList.getJSONObject(0);

                JSONArray healthItems = risk1.getJSONArray("healthItems");
                //JSONArray healthItems1New = new JSONArray() ;

                //异常项--------需要解析--------------------
                JSONObject indexItemException = healthItems.getJSONObject(0);

                try {
                    JSONObject excepJson = new JSONObject();
                    List<AIRiskPapersIndex> papersIndexList = riskPapersIndexService.getNotEmptyByPapersId(paper.getId());
                    /********    只取异常指标 **********/
                    papersIndexList = this.getIndexException(paper, papersIndexList);

                    String inputParams = "年龄：" + paper.getAge() + " 岁。";
                    for (AIRiskPapersIndex paperIndex : papersIndexList) {
                        if (paperIndex.getIndexName().equals("年龄")) {
                            continue;
                        }

                        if (StringUtils.hasText(paperIndex.getIndexValue())) {
                            inputParams += paperIndex.getIndexName() + "，实际值：" + paperIndex.getIndexValue() + "。";
                        }
                    }
                    excepJson.put("data", inputParams);
                    indexItemException.getJSONArray("childItems").set(0, excepJson);

                } catch (Exception e) {
                    log.error(e.toString());
                }

                healthItems.set(0, indexItemException);

                List<AIRiskPapersOptions> listOptions1 = riskPapersOptionsService.getByOptionsPapersTopicList(paper.getId(), Arrays.asList("自述病史", "用药史因素", "饮食习惯"));
                Integer index = 1;
                for (AIRiskPapersOptions papersTopicItem : listOptions1) {
                    JSONObject item = new JSONObject();
                    item.put("clildTitle", papersTopicItem.getTopicName());
                    item.put("isStr", "0");
                    List<Map<String, Object>> options = papersTopicItem.getOptions();
                    JSONArray optionArray = new JSONArray();
                    JSONObject optionJson = new JSONObject();
                    String checkStr = "";
                    List<String> checkItemStrList = new ArrayList<>();
                    for (Map<String, Object> optionItem : options) {
                        if ((Boolean) optionItem.get("checked")) {
                            checkItemStrList.add((String) optionItem.get("value"));
                        }
                    }
                    if (checkItemStrList.size() > 0) {
                        checkStr = String.join("，", checkItemStrList);
                    }
                    optionJson.put("data", checkStr);
                    optionArray.add(optionJson);

                    item.put("childItems", optionArray);

                    healthItems.set(index, item);
                    index++;
                }

                risk1.put("healthItems", healthItems);


                riskList.set(0, risk1);
            } catch (Exception e) {
                log.error(e.toString());
            }


            try {
                //第二项
                JSONObject risk2 = riskList.getJSONObject(2);

                JSONArray healthItems = risk2.getJSONArray("healthItems");

                List<AIRiskPapersOptions> listOptions1 = riskPapersOptionsService.getByOptionsPapersTopicList(paper.getId(), Arrays.asList("生活习惯因素：吸烟年限", "运动锻炼情况", "睡眠情况：睡眠时长", "平均每天睡眠情况", "不良状态"));
                Integer index = 0;
                for (AIRiskPapersOptions papersTopicItem : listOptions1) {
                    JSONObject item = new JSONObject();
                    item.put("clildTitle", papersTopicItem.getTopicName());
                    item.put("isStr", "0");
                    List<Map<String, Object>> options = papersTopicItem.getOptions();
                    JSONArray optionArray = new JSONArray();
                    JSONObject optionJson = new JSONObject();
                    String checkStr = "";
                    List<String> checkItemStrList = new ArrayList<>();
                    for (Map<String, Object> optionItem : options) {
                        if ((Boolean) optionItem.get("checked")) {
                            checkItemStrList.add((String) optionItem.get("value"));
                        }
                    }
                    if (checkItemStrList.size() > 0) {
                        checkStr = String.join("，", checkItemStrList);
                    }
                    optionJson.put("data", checkStr);
                    optionArray.add(optionJson);

                    item.put("childItems", optionArray);

                    healthItems.set(index, item);
                    index++;
                }

                risk2.put("healthItems", healthItems);


                riskList.set(1, risk2);
            } catch (Exception e) {
                log.error(e.toString());
            }


            healthInfo1.put("riskList", riskList);


            healthInfo.set(0, healthInfo1);

            System.out.println(healthInfo);


        } catch (Exception e) {
            log.error(e.toString());
        }

        return healthInfo;


    }


}
